/* See server.go for more details on the ns package.  */
package ns

import (
	"appengine"
	"fmt"
	"net/http"
	"strconv"
	"time"
)

//The name used for the http cookie.
const cookieName = "videoID"

//How long we should keep the cookie in seconds (20 Years)
var twentyYears time.Duration

var videoIdList = []string{
	"eTGU9wA6v5g", "i7Pv4OG3g64", "JP0lhdFj0tY",
	"rFtENxox5HI", "OHkEC4kgYos", "zjWcXxodSyA",
	"rNMN9HjiqWQ", "fne8iRwyoNM", "Ih1yh1mcrZs",
	"LTOggeQPaQE", "dn49EMgfR20", "lDGbigigdDA",
	"sRcx5-unz3E", "-cYOfU0bLG0", "AIQnY_477lA",
	"XeHaXic6A5I", "ay8W4i5Jq4w", "mrE58vUt4Ic",
	"WsVBNzdWals", "VOzUqQMJF-s", "W4af2NW-uiM",
	"qQogCziW4uQ", "HNe2U63FJ3o", "IHXUxqSDqWo",
	"o_wYiqOQcMI", "IyU9uroMoqM", "tp-HauMWKYQ",
	"S-fWlDqrx1E", "SXc0WAV4D94", "G0zyDBafaVg",
	"K-akUvorTcA", "Eoc0VCtyKnA", "XmMvoolvsrc",
	"3xG-Bn3pmcE", "nnSZYYVdkog", "IXQVMH6Gfj8",
	"JygFCzTCZpc", "9frAHrHvpqY", "FjdjQpOdS5M",
	"YcSh6A9O6Dk", "Z0fDijRrW4o", "igoTsQ53JG0",
	"hSgqNNUdYxI", "fr471vj3Rjk", "sZx6ULYdeng",
	"Tz04UFkjEV8", "lxR3mA62fAY", "it6m4mK6vIg",
	"MAT1cNmVZ-g", "0bAV_GVpCgI", "85BS_Izvr_0",
	"FHHHkSiT5nM", "7kw4l0RB-CI", "0C5l0Z5OWPw",
	"EadtizbhzRc", "N25Cx633_MA", "9QD-9O0H4EQ"}

var videoCount int

func init() {
	twentyYears, _ = time.ParseDuration("630720000s")
	http.HandleFunc("/videoID/", videoId)
	if appengine.IsDevAppServer() {
		videoIdList = []string{"fm_6J_8tlyE"}
	}
	videoCount = len(videoIdList)
}

/* The videoId method returns an unused videoId.

We are trying to avoid cache hits for youtube video IDs by keeping track of
which ones have been seen and skipping those.

Note: It isn't clear what we should do for clients that do not accept of return
cookies.  It might be possible to ID them early and use some other kind of
tracking.
*/
func videoId(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	t := time.Now()
	i := 0
	vidCookie, err := r.Cookie(cookieName)
	if err != nil {
		c.Infof("NEW cookie for %d_%s", t, r.RemoteAddr)
	} else {
		i, err = strconv.Atoi(vidCookie.Value)
		if err != nil {
			c.Warningf("BAD cookie for %d_%s = \"%s\"", t, r.RemoteAddr, vidCookie.Value)
			i = 0
		}
		i = (i + 1)
		if i >= videoCount {
			c.Warningf("BIG cookie for %d_%s %d >= %d", t, r.RemoteAddr, i, videoCount)
			i = 0
		}
	}
	vidCookie = &http.Cookie{
		Name:    cookieName,
		Value:   strconv.Itoa(i),
		Expires: t.Add(twentyYears),
	}
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	http.SetCookie(w, vidCookie)
	fmt.Fprint(w, videoIdList[i])
}
